OUTPUT_DIR := ./output
IMAGE := RTOSDemo.out
CURRENT_POJECT := $(notdir $(shell dirname $(shell pwd)))
# The directory that contains the /source and /demo sub directories.
FREERTOS_ROOT = ./../../../

CC = arm-none-eabi-gcc
LD = arm-none-eabi-gcc
SIZE = arm-none-eabi-size
MAKE = make


CFLAGS += $(INCLUDE_DIRS) -nostartfiles -ffreestanding -mthumb -mcpu=cortex-m3 \
		  -Wall -Wextra -g3 -O0 -ffunction-sections -fdata-sections \
		  -MMD -MP -MF"$(@:%.o=%.d)" -MT $@


#
# Kernel build.
#
KERNEL_DIR = $(FREERTOS_ROOT)/FreeRTOS_Source
KERNEL_PORT_DIR += $(KERNEL_DIR)/portable/GCC/ARM_CM3
INCLUDE_DIRS += -I$(KERNEL_DIR)/include \
				-I$(KERNEL_PORT_DIR)
VPATH += $(KERNEL_DIR) $(KERNEL_PORT_DIR) $(KERNEL_DIR)/portable/MemMang
SOURCE_FILES += $(KERNEL_DIR)/tasks.c
SOURCE_FILES += $(KERNEL_DIR)/list.c
SOURCE_FILES += $(KERNEL_DIR)/queue.c
#SOURCE_FILES += $(KERNEL_DIR)/timers.c
SOURCE_FILES += $(KERNEL_DIR)/event_groups.c
SOURCE_FILES += $(KERNEL_DIR)/portable/MemMang/heap_4.c
SOURCE_FILES += $(KERNEL_DIR)/portable/GCC/ARM_CM3/port.c

#
# Application entry point. 
#
EXAMPLES_ROOT = $(FREERTOS_ROOT)/Examples
EXAMPLE_PROJECT = $(EXAMPLES_ROOT)/$(CURRENT_POJECT)
VPATH += $(EXAMPLE_PROJECT)
INCLUDE_DIRS += -I$(EXAMPLE_PROJECT)
SOURCE_FILES += (EXAMPLE_PROJECT)/main.c
SOURCE_FILES += ./startup_gcc.c

# Lightweight print formatting to use in place of the heavier GCC equivalent.
SOURCE_FILES += ./printf-stdarg.c


#Supporting Functions
SUPPORTING_FUNCTIONS = $(FREERTOS_ROOT)/Supporting_Functions
VPATH += $(SUPPORTING_FUNCTIONS)
INCLUDE_DIRS += -I$(SUPPORTING_FUNCTIONS)
SOURCE_FILES += (SUPPORTING_FUNCTIONS)/supporting_functions.c


#Create a list of object files with the desired output directory path.
OBJS = $(SOURCE_FILES:%.c=%.o)
OBJS_NO_PATH = $(notdir $(OBJS))
OBJS_OUTPUT = $(OBJS_NO_PATH:%.o=$(OUTPUT_DIR)/%.o)

#Create a list of dependency files with the desired output directory path.
DEP_FILES := $(SOURCE_FILES:%.c=$(OUTPUT_DIR)/%.d)
DEP_FILES_NO_PATH = $(notdir $(DEP_FILES))
DEP_OUTPUT = $(DEP_FILES_NO_PATH:%.d=$(OUTPUT_DIR)/%.d)

all: $(OUTPUT_DIR) | $(OUTPUT_DIR)/$(IMAGE)

$(OUTPUT_DIR):
	@mkdir -p $(OUTPUT_DIR)

%.o : %.c
$(OUTPUT_DIR)/%.o : %.c $(OUTPUT_DIR)/%.d Makefile
	$(CC) $(CFLAGS) -c $< -o $@

$(OUTPUT_DIR)/$(IMAGE): ./mps2_m3.ld $(OBJS_OUTPUT) Makefile
	@echo ""
	@echo ""
	@echo "--- Final linking ---"
	@echo ""
	$(LD) $(OBJS_OUTPUT) $(CFLAGS) -Xlinker --gc-sections -Xlinker -T ./mps2_m3.ld \
		-Xlinker -Map=$(OUTPUT_DIR)/RTOSDemo.map -specs=nano.specs \
		-specs=nosys.specs -specs=rdimon.specs -o $(OUTPUT_DIR)/$(IMAGE)
	$(SIZE) $(OUTPUT_DIR)/$(IMAGE)

$(DEP_OUTPUT):
include $(wildcard $(DEP_OUTPUT))

clean:
	rm -f $(OUTPUT_DIR)/$(IMAGE) $(OUTPUT_DIR)/*.o $(OUTPUT_DIR)/*.d

#use "make print-[VARIABLE_NAME] to print the value of a variable generated by
#this makefile.
print-%  : ; @echo $* = $($*)

.PHONY: all clean
